package happy.town.threeBook;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/*
    JDBC工具类
 */
public class JDBCUtils {
    //1.私有构造方法
    public JDBCUtils() {

    }

    //2.声明配置信息变量
    public static String driverClass;
    public static String url;
    public static String username;
    public static String password;
    public static Connection conn;

    //创建Properties集合，加载流对象的信息
    static Properties prop = new Properties();

    //3.静态代码块中实现加载配置文件和注册驱动
    static {
        try {
            //通过类加载器返回配置文件的字节流
            InputStream is = JDBCUtils.class.getResourceAsStream("config.properties");


            prop.load(is);

            //获取信息为变量赋值
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");

            //注册驱动
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //4.获取数据库连接的方法
    public static Connection getConnection() {
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

    //5.释放资源的方法
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, Statement stat) {
        close(conn, stat, null);
    }
}
